package com.ecmwidgets.test;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;

import com.ibm.json.java.JSONObject;
import com.ibm.jvm.util.ByteArrayOutputStream;

public class RESTUtilOnATOM extends RESTUtil{

	String hostname = "localhost";
	String port = "9443";
	String username = "administrator";
	String password = "filenet";
	HttpClient client = null;
	HttpClientParams params = null;
	String loginURL="";



	protected void init(Properties props){
		this.setHostname(props.getProperty("HOSTNAME").toString());
		this.setPort(props.getProperty("PORT").toString());
		this.setUsername(props.getProperty("USERNAME").toString());
		this.setPassword(props.getProperty("PASSWORD").toString());
		loginURL = "https://"+getHostname()+":"+getPort()+"/mashuphub/";
		
        this.client = new HttpClient();
		client.getState().setCredentials(
				new AuthScope(this.getHostname(), Integer.parseInt(this.getPort()),AuthScope.ANY_REALM),
				new UsernamePasswordCredentials(this.getUsername(), this.getPassword()));
		HttpClientParams params = new HttpClientParams();
		params.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
		
	        Map<String, String> cookies;
			try {
				cookies = MashupMakerProxy.loginMashupMaker(loginURL,getUsername(),getPassword());

	        
	        Protocol mashupHttps = new Protocol("https", new MashupSSLProtocolSocketFactory(), Integer.parseInt(getPort()));
	        Protocol.registerProtocol("https", mashupHttps);

			params.setParameter("LtpaToken2", cookies.get("LtpaToken2").toString());
			params.setParameter("LtpaToken", cookies.get("LtpaToken2").toString());

			this.client.setParams(params);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
	}
	
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		/*
		String restURL = "https://localhost:9443/mashuphub/client/ui/details/entryid/46";
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", "localhost");
        prop.setProperty("PORT", "9443");
        prop.setProperty("USERNAME", "administrator");
        prop.setProperty("PASSWORD", "filenet");
        RESTUtilOnJSON util = new RESTUtilOnJSON(prop);
        //util.executeGet(restURL);
        String content = "pluginid=19";
        JSONObject response =util.executePost("https://localhost:9443/mashuphub/client/plugin/editor/json/1",content.toString());
        
        String result= response.get("result").toString();
        JSONObject obj_id = JSONObject.parse(result);
        result=obj_id.get("object_id").toString();
        System.out.println(result);
*/

	}
	public String executeGet(String url){
		String msg = "";
		System.out.println(url);
		try{
			HttpMethod httpMethod = new GetMethod(url);
			
			httpMethod.setDoAuthentication(true);
			this.client.executeMethod(httpMethod);
			System.out.println("Status code: " + httpMethod.getStatusCode());
			Header contentTypeHeader = httpMethod.getResponseHeader("content-type");
//			System.out.println("Mimetype: " + contentTypeHeader.getValue());
//			System.out.println("Response: " + httpMethod.getResponseBodyAsString());
			msg = httpMethod.getResponseBodyAsString();
//			InputStream stream = httpMethod.getResponseBodyAsStream();
//			
//	        BufferedReader br = new BufferedReader(new InputStreamReader(stream));   
//	        StringBuffer resBuffer = new StringBuffer();   
//	        String resTemp = "";   
//	        while((resTemp = br.readLine()) != null){   
//	            resBuffer.append(resTemp);   
//	        }   
//	        msg = resBuffer.toString();  

//			ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
//			int   i=-1; 
//			while((i=stream.read())!=-1){ 
//				baos.write(i); 
//			} 
//			msg = baos.toString(); 

			httpMethod.releaseConnection(); 
		}catch (HttpException he){
			he.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return msg;
		
	}

	public InputStream executeGet2(String url) throws HttpException, IOException{
		HttpMethod httpMethod = new GetMethod(url);
		
		httpMethod.setDoAuthentication(true);
		this.client.executeMethod(httpMethod);
		System.out.println("Status code: " + httpMethod.getStatusCode());
//		Header contentTypeHeader = httpMethod.getResponseHeader("content-type");
		InputStream stream = httpMethod.getResponseBodyAsStream();
		httpMethod.releaseConnection(); 
		return stream;
		
	}


	public String executePost(String url, String content){
		String response ="";
		try{
			PostMethod postMethod = new PostMethod(url);
			postMethod.setDoAuthentication(true);
			Header mtHeader1 = new Header();
			mtHeader1.setName("content-type");
			mtHeader1.setValue("application/xml; charset=UTF-8");
			postMethod.addRequestHeader(mtHeader1);
			String cred = this.getUsername() + ":" + this.getPassword();
			String authHeader = "Basic "+ new String(Base64.encodeBase64(cred.getBytes()));
			Header mtHeader2 = new Header();
			mtHeader2.setName("Authorization");
			mtHeader2.setValue(authHeader);
			postMethod.addRequestHeader(mtHeader2);
			
			RequestEntity requestEntity = new StringRequestEntity(content,"application/xml","UTF-8");
			postMethod.setRequestEntity(requestEntity);
			postMethod.setDoAuthentication(true);	
			
			this.client.executeMethod(postMethod);

			System.out.println("Status code: " + postMethod.getStatusCode());
			System.out.println("Status Text: " + postMethod.getStatusText());
			Header contentTypeHeader = postMethod.getResponseHeader("content-type");
			//System.out.println("Mimetype: " + contentTypeHeader.getValue());
			response = postMethod.getResponseBodyAsString();
			System.out.println("Response: " + response);
			postMethod.releaseConnection(); 
		}catch (HttpException he){
			he.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return response;
	}


	public String executePut(String url, String content){
		String response ="";
		try{			
			PutMethod putMethod = new PutMethod(url);
			putMethod.setDoAuthentication(true);
			Header mtHeader1 = new Header();
			mtHeader1.setName("content-type");
			mtHeader1.setValue("application/xml; charset=UTF-8");
			putMethod.addRequestHeader(mtHeader1);
			String cred = this.getUsername() + ":" + this.getPassword();
			String authHeader = "Basic "+ new String(Base64.encodeBase64(cred.getBytes()));
			Header mtHeader2 = new Header();
			mtHeader2.setName("Authorization");
			mtHeader2.setValue(authHeader);
			putMethod.addRequestHeader(mtHeader2);
			
			RequestEntity requestEntity = new StringRequestEntity(content,"application/xml","UTF-8");
			putMethod.setRequestEntity(requestEntity);
			putMethod.setDoAuthentication(true);	
			
			this.client.executeMethod(putMethod);
	
			System.out.println("Status code: " + putMethod.getStatusCode());
			System.out.println("Status Text: " + putMethod.getStatusText());
			Header contentTypeHeader = putMethod.getResponseHeader("content-type");
			//System.out.println("Mimetype: " + contentTypeHeader.getValue());
			response = putMethod.getResponseBodyAsString();
			System.out.println("Response: " + response);
			putMethod.releaseConnection(); 
		}catch(Exception e){
			
		}
		return response;
	}
	
	public void closeConnection(){
		this.client=null;
	}
	public void setHostname(String hostname){
		this.hostname=hostname;
	}
	public String getHostname(){
		return this.hostname;
	}

	public void setPort(String port){
		this.port=port;
	}
	public String getPort(){
		return this.port;
	}
	
	public void setUsername(String username){
		this.username=username;
	}
	public String getUsername(){
		return this.username;
	}
	
	public void setPassword(String password){
		this.password=password;
	}
	
	public String getPassword(){
		return this.password;
	}
}
